package fr.inserm.um915.jimpute.model;

import java.util.Comparator;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import com.sleepycat.je.DatabaseEntry;

public class ChromPosition
	implements Comparable<ChromPosition>
	{
	private byte chrom;
	private int position;
	
	public static class ChromPositionComparator implements Comparator<byte[]>
		{
		@Override
		public int compare(byte[] o1, byte[] o2)
			{
			Binding b=new ChromPosition.Binding();
			ChromPosition s1= b.entryToObject(new DatabaseEntry(o1));
			ChromPosition s2= b.entryToObject(new DatabaseEntry(o2));
			return s1.compareTo(s2);
			}
		}
	
	public static class Binding extends TupleBinding<ChromPosition> 
		{
		@Override
		public void objectToEntry(ChromPosition o, TupleOutput out)
			{
			out.writeByte((byte)o.chrom);
			out.writeInt(o.position);
			}
			
		@Override
		public ChromPosition entryToObject(TupleInput in)
			{
			byte s= in.readByte();
			int p=in.readInt();
			return new ChromPosition(s, p);
			}
		};
	
	public static final Binding	BINDING=new Binding();
	
	public ChromPosition(ChromPosition cp)
		{
		this.chrom=cp.chrom;
		this.position=cp.position;
		}

	
	public ChromPosition(byte chrom,int position)
		{
		this.chrom=chrom;
		this.position=position;
		}
	
	public ChromPosition(String chrom,int position)
		{
		this((byte)Chromosome.valueOf(chrom).ordinal(),position);
		}
	
	

	
	@Override
	public int compareTo(ChromPosition o)
		{
		int i= chrom - o.chrom;
		if(i!=0) return i;
		i= position-o.position;
		return i;
		}
	
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + chrom;
		result = prime * result + position;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ChromPosition other = (ChromPosition) obj;
		return this.compareTo(other)==0;
	}
	
	public byte getChromosomeIdx()
		{
		return this.chrom;
		}
	

	public int getPosition()
		{
		return position;
		}
	
	@Override
	public String toString()
		{
		return Chromosome.values()[this.chrom].name()+":"+position;
		}
	
	}